package com.limetalks.servlet;

import java.io.IOException;

import javax.persistence.Persistence;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.limetalks.dao.StreamDAO;
import com.limetalks.data.Category;
import com.limetalks.data.Stream;
import com.limetalks.data.Stream.StreamStatus;
import com.limetalks.data.User;
import com.limetalks.util.GlobalStrings;


public class AddStreamServlet extends HttpServlet {
	
	private static final long serialVersionUID = 1L;
    
	private StreamDAO streamDao;
	
    public AddStreamServlet() {
        super();
        streamDao = new StreamDAO(Persistence.createEntityManagerFactory(GlobalStrings.PERSISTENCE_UNIT_NAME));
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		request.setCharacterEncoding("utf-8");
		String name = request.getParameter("name");
		Object user = request.getSession().getAttribute("user");
		String categoryId = request.getParameter("category");
		String imageFileName = request.getParameter("image");
		
		if(user != null) {
			
			Stream stream = new Stream();
			stream.setName(name);
			stream.setMaster((User)user);
			stream.setStatus(StreamStatus.CURRENT);
			stream.setImage(imageFileName);
			
			Category category = new Category();
			category.setId(Integer.valueOf(categoryId));
			stream.setCategory(category);
							
			try{
				streamDao.save(stream);
				
				System.out.println("!!!! New Stream created: " + stream);
				
				response.setContentType("application/json");
				response.getOutputStream().print("{id:"+stream.getId()+"}");
			}catch (Exception e) {
				e.printStackTrace();
				response.sendError(400, "Stream creation failed");
				response.setContentType("application/json");
			}
		} else {
			response.sendError(500, "Login");
			response.setContentType("application/json");
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request,response);
	}

}
